package com.example.xjtuse_pc.mobilesafe;


import android.app.Activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xjtuse_pc.db.dao.AppLockDao;
import com.example.xjtuse_pc.domain.AppInfo;
import com.example.xjtuse_pc.engine.AppInfoProvider;
import com.example.xjtuse_pc.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;


public class AppManagerActivity extends Activity implements View.OnClickListener {
    private boolean True = true;
    private TextView tv_avail_rom, tv_avail_sd, tv_status;
    private LinearLayout ll_loading;
    private ListView lv_app_manager;
    private List<AppInfo> appInfos;
    private LinearLayout ll_start, ll_share, ll_uninstall;
    private MyAdapter adapter;
    //弹出悬浮窗口
    private PopupWindow popupWindow;
    //用户应用程序
    private List<AppInfo> userAppInfos;
    //系统应用程序
    private List<AppInfo> systemAppInfos;
    //每个listview条目信息
    private AppInfo api;
    private AppLockDao ad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_manager);
        ad=new AppLockDao(this);
        tv_status = (TextView) findViewById(R.id.tv_status);
        tv_avail_rom = (TextView) findViewById(R.id.tv_avail_rom);
        tv_avail_sd = (TextView) findViewById(R.id.tv_avail_sd);
        long sdsize = getAvailSpace(Environment.getExternalStorageDirectory().getAbsolutePath());
        long romsize = getAvailSpace(Environment.getDataDirectory().getAbsolutePath());
        tv_avail_rom.setText("内存可用:" + android.text.format.Formatter.formatFileSize(AppManagerActivity.this, romsize));
        tv_avail_sd.setText("SD卡可用:" + android.text.format.Formatter.formatFileSize(AppManagerActivity.this, sdsize));
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        lv_app_manager = (ListView) findViewById(R.id.lv_app_manager);

        getListMessage();

        /**
         * listview滚动监听
         */
        lv_app_manager.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (userAppInfos != null && systemAppInfos != null) {
                    if (firstVisibleItem > userAppInfos.size()) {
                        tv_status.setText("系统程序：" + systemAppInfos.size() + "个");
                    } else {
                        tv_status.setText("用户程序：" + userAppInfos.size() + "个");
                    }
                }
                dismissPopWindow();

            }
        });

        /**
         * 设置listview点击事件
         */
        lv_app_manager.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0 || position == (userAppInfos.size() + 1)) {
                    return;
                } else if (position <= userAppInfos.size()) {//用户程序
                    int newposition = position - 1;
                    api = userAppInfos.get(newposition);
                } else {
                    int newposition = position - 2 - userAppInfos.size();
                    api = systemAppInfos.get(newposition);
                }


                dismissPopWindow();

                View tv = View.inflate(AppManagerActivity.this, R.layout.popup_app_item, null);
                ll_start = (LinearLayout) tv.findViewById(R.id.ll_start);
                ll_share = (LinearLayout) tv.findViewById(R.id.ll_share);
                ll_uninstall = (LinearLayout) tv.findViewById(R.id.ll_uninstall);

                ll_start.setOnClickListener(AppManagerActivity.this);
                ll_share.setOnClickListener(AppManagerActivity.this);
                ll_uninstall.setOnClickListener(AppManagerActivity.this);

                popupWindow = new PopupWindow(tv, -2, -2);
                //动画效果必须窗体有背景颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                int[] location = new int[2];
                view.getLocationInWindow(location);
                int dip = 70;
                int px = DensityUtil.dip2px(AppManagerActivity.this, dip);
                popupWindow.showAtLocation(parent, Gravity.TOP | Gravity.LEFT, px, location[1]);

                ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa.setDuration(1000);
                AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
                aa.setDuration(1000);
                AnimationSet as = new AnimationSet(false);
                as.addAnimation(sa);
                as.addAnimation(aa);
                tv.startAnimation(as);
            }
        });

        /**
         * listview长按点击 实现程序上锁
         */
        lv_app_manager.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || position == (userAppInfos.size() + 1)) {
                    return true;
                } else if (position <= userAppInfos.size()) {
                //用户程序
                    int newposition = position - 1;
                    api = userAppInfos.get(newposition);
                } else {
                    int newposition = position - 2 - userAppInfos.size();
                    api = systemAppInfos.get(newposition);
                }
                ViewHolder vh= (ViewHolder) view.getTag();
                //更改程序锁
                if(ad.find(api.getPicname())){
                    ad.delet(api.getPicname());
                    vh.iv_app_status.setImageResource(R.drawable.unlock);

                }else {
                    ad.add(api.getPicname());
                    vh.iv_app_status.setImageResource(R.drawable.lock);
                }


                return true;
            }
        });

    }

    /**
     * listview获取所有app数据
     */
    private void getListMessage() {
        ll_loading.setVisibility(View.VISIBLE);

        new Thread(new Runnable() {
            @Override
            public void run() {

                appInfos = AppInfoProvider.getAppInfos(AppManagerActivity.this);
                userAppInfos = new ArrayList<AppInfo>();
                systemAppInfos = new ArrayList<AppInfo>();
                for (AppInfo ai : appInfos) {
                    True = ai.isUserApp() ? userAppInfos.add(ai) : systemAppInfos.add(ai);
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (adapter == null) {
                            adapter = new MyAdapter();
                            lv_app_manager.setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        ll_loading.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }).start();
    }



    private void dismissPopWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }



    /**
     * Onclick
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_start:
                Log.i("join", api.getName() + "-1");
                startApp();
                break;
            case R.id.ll_share:
                Log.i("join", api.getName() + "-2");
                shareApp();
                break;
            case R.id.ll_uninstall:
                Log.i("join", api.getName() + "-3");
                if (api.isUserApp()) {
                    uninstallApp();
                } else {
                    Toast.makeText(AppManagerActivity.this, "系统程序只有root权限才可卸载", Toast.LENGTH_SHORT).show();
                }

                break;
        }

    }

    /**
     * 分享应用
     */
    private void shareApp() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.SEND");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款应用：" + api.getName());
        startActivity(intent);
    }

    /**
     * 卸载应用
     */
    private void uninstallApp() {
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.addCategory("android.intent.category.DEFAULT");
//        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//        startActivity(intent);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.View");
        intent.setAction("android.intent.action.DELETE");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("package:" + api.getPicname()));
        startActivityForResult(intent, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getListMessage();
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 开启一个App
     */
    private void startApp() {
//       //查询出所有app
        PackageManager pm = getPackageManager();
//        Intent intent=new Intent();
//        intent.setAction("android.intent.action.MAIN");
//        intent.addCategory("android.intent.category.LAUNCHER");
//        List<ResolveInfo> info=pm.queryIntentActivities(intent,PackageManager.GET_INTENT_FILTERS);
//        for(ResolveInfo i:info) {
//            Log.i("join", i.activityInfo.packageName);
//        }
//        启动一个app
        Intent intent = pm.getLaunchIntentForPackage(api.getPicname());
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(AppManagerActivity.this, "不能启动该应用", Toast.LENGTH_SHORT).show();
        }
    }


    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return userAppInfos.size() + systemAppInfos.size() + 2;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view;
            ViewHolder vh;
            AppInfo ai;
            if (position == 0) {
                //显示用户程序数量
                TextView tv = new TextView(AppManagerActivity.this);
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("用户程序：" + userAppInfos.size() + "个");
                return tv;
            } else if (position == (userAppInfos.size() + 1)) {
                //显示用户程序数量
                TextView tv = new TextView(AppManagerActivity.this);
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("系统程序：" + systemAppInfos.size() + "个");
                return tv;
            } else if (position <= userAppInfos.size()) {
                int newp = position - 1;
                ai = userAppInfos.get(newp);

            } else {
                int newposition = position - 2 - userAppInfos.size();
                ai = systemAppInfos.get(newposition);
            }


//            if(position<userAppInfos.size()){
//                //用户程序位置
//                ai=userAppInfos.get(position);
//            }else{
//                //系统程序位置
//                int newposition=position-userAppInfos.size();
//                ai=systemAppInfos.get(newposition);
//            }

            if (convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                vh = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(AppManagerActivity.this, R.layout.list_item_app, null);

                vh = new ViewHolder();
                vh.iv_icon = (ImageView) view.findViewById(R.id.iv_app_icon);
                vh.tv_name = (TextView) view.findViewById(R.id.tv_app_name);
                vh.tv_location = (TextView) view.findViewById(R.id.tv_app_location);
                vh.iv_app_status = (ImageView) view.findViewById(R.id.iv_app_status);
                view.setTag(vh);
            }

            vh.iv_icon.setImageDrawable(ai.getIcon());
            vh.tv_name.setText(ai.getName());
            if (ai.isRom()) {
                vh.tv_location.setText("手机内存");

            } else {

                vh.tv_location.setText("外部存储");
            }

            if(ad.find(ai.getPicname())){
                vh.iv_app_status.setImageResource(R.drawable.lock);
            }else {
                vh.iv_app_status.setImageResource(R.drawable.unlock);
            }

            return view;
        }
    }

    static class ViewHolder {
        TextView tv_name;
        TextView tv_location;
        ImageView iv_icon;
        ImageView iv_app_status;
    }


    /**
     * 获取目录可用空间
     *
     * @param path 目录路径
     * @return 空间大小
     */
    public long getAvailSpace(String path) {
        //得到空间大小的api
        StatFs sf = new StatFs(path);
        //获取分区个数
        long size = sf.getBlockSize();
        long count = sf.getBlockCount();

        return size * count;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissPopWindow();
    }
}
